from flask import Flask, request, jsonify
import os

from werkzeug.utils import secure_filename
from flask_cors import CORS  

app = Flask(__name__)
UPLOAD_FOLDER = '/data7t/uploadfile/image'  # 请替换为你的上传文件夹路径
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app)

@app.route('/upload', methods=['POST','OPTIONS'])
def upload_file():

    # 支持OPTIONS预检请求，并返回跨域支持
    if request.method == 'OPTIONS':
          response = jsonify({'message': 'OPTIONS request received'})
          # 设置CORS相关的响应头
          response.headers.add('Access-Control-Allow-Origin', '*')
          response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
          response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
          return response,200
 
    print(request.files)

    if 'file' not in request.files:
        response = jsonify({'error': 'No file part in the request'})
        return response, 400
    file = request.files['file']

    if file.filename == '':
        response = jsonify({'error': 'No selected file'})
        return response, 400

    if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        response = jsonify({'filename': filename})
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        return response, 200

# curl 测试
# curl -X POST -F "file=@/Users/liuminghao/Desktop/jieping/jp2023-11-22 21.42.17.jpg" http://192.168.31.231:8091/upload




if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8091, debug=True)
